# coding=utf-8
import os
from ShellUtils import shell_cmd
from ShellUtils import shell_cmd_with_ret


def repo_clean_all_change(project_dir):
    shell_cmd("cd %s; repo --no-pager forall -c 'git reset --hard remotes/m/sw'" % project_dir)


def get_repo_dir(abs_dir, maxdepth=3):
    ret, msg = shell_cmd_with_ret("cd %s; find -maxdepth %s -name .repo" % (abs_dir, maxdepth))
    if ret and str(ret).find(".repo") != -1:
        return os.path.join(abs_dir, ret)
    return None


def get_repo_all_gits(repo_dir):
    if repo_dir:
        ret, msg = shell_cmd_with_ret("cd %s; find -maxdepth 3 -name project.list" % repo_dir)
        if str(ret).find("project.list") != -1:
            with open(os.path.join(repo_dir, ret)) as f:
                return f.readlines()
    return None


def get_android_base_dir(project_dir, maxdepth=2):
    ret, msg = shell_cmd_with_ret("cd %s; find -maxdepth %s -name frameworks" % (project_dir, maxdepth))
    split = ret.split(os.linesep)
    if len(split) >= 1:
        for spl in split:
            if os.path.exists(os.path.join(project_dir, spl.strip(), "support", "api")):  # frameworks/support/api
                return spl.strip() + os.sep + ".."


def get_git_by_path(path, android_base_dir):
    """
    path: path under android_base_dir
    """
    if path.startswith(os.sep):
        path = path[1:]

    head, tail = os.path.split(path)
    while len(head) > 0:
        head, tail = os.path.split(head)
        if os.path.exists(os.path.join(android_base_dir, head, ".git")):
            return head
    return None


class RepoHelper:
    def __init__(self, project_dir):
        self.project_dir = project_dir
        self.android_base_dir = get_android_base_dir(project_dir)
        self.repo_dir = get_repo_dir(self.project_dir)
        self.all_gits = get_repo_all_gits(self.repo_dir)

    def get_android_abs_dir(self):
        return os.path.join(self.project_dir, self.android_base_dir)

    def get_repo_dir(self):
        return self.repo_dir

    def get_gits(self):
        return self.all_gits

    def get_git_by_path(self, path):
        return get_git_by_path(path, os.path.join(self.project_dir, self.android_base_dir))
